package util;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.example.administrator.text.AppointTimeActivity;
import com.example.administrator.text.R;
import org.apache.log4j.Logger;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import app.MyApplication;
import data.SharedPreferencesUtils;
import static app.MyApplication.mFWQIP;

/**
 * Created by liuxiaobin on 2016/12/14
 * 获取代理服务器 并验证 并验证网络情况
 *  <!-- //南山街道办  http://139.199.72.236:8080/proxyservice/TransferServlet</item>-->
 */
public class AgentIp {

    private static AgentIp mAgentIp;
    private Context mContext;
    private WebView mWebView;
    private String[] mProjectIP;
    private Timer mTimer;
    private String mUri;
    private boolean isTypeNetWorkstate;   //判断网络是否回调出去 有时会及成功有失败
    private boolean isTransferState;    //是否回调出去
    private boolean isAltairWifi = false;      // 代理是否通
    private String mFwq,mMac;                //记录代理地址和mac
    private boolean mJumd = true;          //判断第几次加载网页
    private final String[] mNasid = {""};
    private Logger mLogger = Logger.getLogger(AgentIp.class);
    private OnAgentIpItemClickListener mOnAgentIpItemClickListener;
    private OnNetworkStateClickListener mOnNetworkStateClickListener;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mLogger.info("handleMessage()...时间到了+isTransferState..."+isTransferState+"..isAltairWifi.."+isAltairWifi);
            switch (msg.what){
                case 1:
                    if(!isTransferState){
                        isTransferState = true;
                        mWebView.destroy();
                        mWebView.removeAllViews();
                       if(isAltairWifi){
                           mOnAgentIpItemClickListener.onItemClick(mFwq);
                       }else {
                           if(mFwq.equals("")){
                               mOnAgentIpItemClickListener.onItemClick("没有查到");
                           }else {
                               mOnAgentIpItemClickListener.onItemClick(mFwq);
                           }
                       }
                    }
                    break;
                }
        }
    };

    private AgentIp(Context context){
        this.mContext = context.getApplicationContext();
    }

    public static AgentIp newInstance(Context context){

        if(mAgentIp == null){
            synchronized (AgentIp.class){
                if(mAgentIp == null){
                    mAgentIp = new AgentIp(context);
                    return mAgentIp;
                }
            }
        }
        return mAgentIp;
    }

    /**
     * 开始寻找ip
     */
    public void getIp(OnAgentIpItemClickListener onAgentIpItemClickListener){

        isTransferState = false;
        isAltairWifi = false;
        SharedPreferencesUtils.setParam(mContext,HomeUtil.appNetWorkstate,false);
        mJumd = true;
        mFwq = "";
        mOnAgentIpItemClickListener = onAgentIpItemClickListener;
        mMac = getInformation.getNewGetInformation(mContext).getIMAC();
        getloop();
        agentIP(mFWQIP,2);
        getPortal();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                mHandler.sendMessage(message);
            }
        };

        if(mTimer == null){
            mTimer = new Timer();
        }
        mTimer.schedule(timerTask,15000);
    }

    /**
     * 刷新网络状态 回调结果
     */
    public void setNetWorkstate1(){
        agentIP(mFWQIP,1);

    }

    /**
     * 刷新网络状态 回调结果
     */
    public void setNetWorkstate2(OnNetworkStateClickListener onAgentIpItemClickListener){
        mOnNetworkStateClickListener = onAgentIpItemClickListener;
        isTypeNetWorkstate = false;
        agentIP(mFWQIP,3);

    }

    public boolean isAltairWifi() {
        return isAltairWifi;
    }

    public boolean isNetWorkstate() {
        boolean netWorkstate = (boolean)SharedPreferencesUtils.getParam(mContext,HomeUtil.appNetWorkstate,true);
        return netWorkstate;
    }

    public void setAltairWifi(boolean altairWifi) {
        isAltairWifi = altairWifi;
    }

    /**
     *  get调用 loopIP（）;
     *  fwq 为上一次记录的代理服务器地址
     */
    private void getloop(){
        mProjectIP = mContext.getResources().getStringArray(R.array.FWQ);
        for (int i = 0; i <mProjectIP.length ; i++) {
            loopIP(mProjectIP[i]);
        }
    }

    /**
     * 并发 本地代理地址
     */
    private void loopIP(final String ip){

        HashMap<String,Object> json = new HashMap<>();
        final String id = (String) SharedPreferencesUtils.getParam(mContext, HomeUtil.mUseridDB, "");
        if(id.equals("")){
            json.put("userid",0);
        }else { json.put("userid", id);}
        json.put("visitType",1);
        json.put("ip",getInformation.getNewGetInformation(mContext).getI_IP());
        json.put("mac",getInformation.getNewGetInformation(mContext).getIMAC());
        json.put("apMac",getInformation.getNewGetInformation(mContext).getWiFiMac());
        json.put("apName",getInformation.getNewGetInformation(mContext).getWIFIName());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(json); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngVersion_isAlive,stringJson,"null","0",time);
        Map map = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,"null","0",Url.mStirngVersion_isAlive,stirngSign,time);
        LogUtil.eE(".............loopIP()......",ip);
        GreenTreeNetworkUtil.getInstance().doPost(mContext,ip,8000,map, new RequestDataCallback() {
                @Override public void onSuccess(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.getInt("code") == 1) {
                            mLogger.info("agentIP()...onSuccess.."+response+"..ip.."+ip);
                            if (jsonObject.has("siteAreaid")){
                                int areaid = jsonObject.getInt("siteAreaid");
                                if(areaid != 0){
                                    mLogger.info("loopIP()...onSuccess.."+response+"..isTransferState.."+isTransferState+"ip"+ip);
                                    MyApplication.getApp().setSiteAreaid(jsonObject.getInt("siteAreaid"));
                                    if(!isTransferState){
                                        isAltairWifi = true;
                                        mFwq = ip;
                                        if(StringUtil.getStringUtilNew().judgeMac(mMac)){
                                            isTransferState = true;
                                            mWebView.destroy();
                                            mWebView.removeAllViews();
                                            mOnAgentIpItemClickListener.onItemClick(ip);
                                        }else {
                                            mLogger.info("agentIP()...onSuccess.. apMac 为空");
                                        }
                                    }
                                }else {
                                    mFwq = ip;
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override public void onFailure(Throwable error) {
                    mLogger.info("agentIP()...onFailure.."+error.getMessage()+"..ip.."+ip);
                }});
    }

    /**
     * 测试域名
     * 1 为不用返回结果  3需要返回结果  2不返回结果 但该1秒后要检查下
     */
    private void agentIP(final String fwq,final int type){
        String stringJson ="{}"; //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngVersion_isAlive,stringJson,"null","0",time);
        Map map = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,"null","0",Url.mStirngVersion_isAlive,stirngSign,time);
        GreenTreeNetworkUtil.getInstance().doPost(mContext,fwq,1500,map,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 1) {
                        SharedPreferencesUtils.setParam(mContext,HomeUtil.appNetWorkstate,true);
                        mLogger.info("测试网络结果"+response+"..isTransferState.."+isTransferState+"fwq"+fwq);
                        if(type == 3){
                                isTypeNetWorkstate = true;
                                mOnNetworkStateClickListener.onClick(true);
                        }
                        if(type == 2){
                            if(!isAltairWifi()){
                                mFwq = fwq;
                                  HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {@Override public void run() {
                                     if(!isAltairWifi()){
                                         if(!isTransferState){
                                             isTransferState = true;
                                             mWebView.destroy();
                                             mWebView.removeAllViews();
                                             mOnAgentIpItemClickListener.onItemClick(mFWQIP);
                                            }
                                         }
                                     }
                                },3000);
                            }
                        }
                        if(type ==1){
                            if(Url.getUrlNew().isNotification()){
                                HashMap<String,Object> hashMap = new HashMap<>();
                                hashMap.put("code","WiFi");
                                hashMap.put("target",AppointTimeActivity.mNetWorkstate);
                                hashMap.put("sign","UpdateUI");
                                String stringJson = StringUtil.getStringUtilNew().hashMapToJson(hashMap); //参数包
                                EventBus.getDefault().post(stringJson);
                            }
                        }

                    }else {
                        if(type == 3){
                            LogUtil.eE("gggggg","onSuccess....2");
                            if(!isTypeNetWorkstate){
                                isTypeNetWorkstate = true;
                                mOnNetworkStateClickListener.onClick(false);
                            }
                        }
                        SharedPreferencesUtils.setParam(mContext,HomeUtil.appNetWorkstate,false);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    if(type == 3){
                        if(!isTypeNetWorkstate){
                            isTypeNetWorkstate = true;
                            mOnNetworkStateClickListener.onClick(false);
                        }
                    }
                    SharedPreferencesUtils.setParam(mContext,HomeUtil.appNetWorkstate,false);
                }
            }

            @Override public void onFailure(Throwable error) {
                if(type == 3){
                    LogUtil.eE("gggggg","onSuccess....4");
                    if(!isTypeNetWorkstate){
                        isTypeNetWorkstate = true;
                        mOnNetworkStateClickListener.onClick(false);
                    }
                }
                SharedPreferencesUtils.setParam(mContext,HomeUtil.appNetWorkstate,false);
            }});
    }

    /**
     * 去加载portal页面
     */
    private void getPortal(){
        LogUtil.eE("","getPortal()..");
        final String[] usermac = {""};
        mWebView = new WebView(mContext);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://www.szaltair.com/");
        AgentIp.AgentIpWewView agentIpWewView = new AgentIp.AgentIpWewView();
        mWebView.addJavascriptInterface(agentIpWewView,agentIpWewView.getInterface());
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        mWebView.setWebViewClient(new WebViewClient(){
            @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {

                LogUtil.eE("",url+"mJumd"+mJumd);
                try {
                    if(mJumd){
                        if(url.contains("/MobileAltair/")){
                            String string = url.substring(url.indexOf("?")+1,url.length());
                            if(string.contains("ap-mac=")){
                                //String ap_mac = string.substring(string.indexOf("ap-mac=")+7,string.indexOf("&nasip"));
                            }
                            if(string.contains("usermac=")){
                                mJumd = false;
                                String mac = string.substring(string.indexOf("usermac=")+8,string.length());
                                mac = mac.substring(0,mac.indexOf("&"));
                                SharedPreferencesUtils.setParam(mContext, HomeUtil.mFWQMAC, mac);
                            }

                            if(string.contains("wlanusermac")){
                                mJumd = false;
                                String mac = string.substring(string.indexOf("wlanusermac=")+12,string.length());
                                mac = mac.substring(0,mac.indexOf("&"));
                                SharedPreferencesUtils.setParam(mContext, HomeUtil.mFWQMAC,mac);
                            }

                            if(string.contains("nasid")){
                                mNasid[0] = string.substring(string.indexOf("nasid")+6,string.length());
                                if(mNasid[0].contains("/")){
                                    mNasid[0] = mNasid[0].replaceAll("/","#");
                                }
                            }
                            if(mJumd){
                                if(getInformation.getNewGetInformation(mContext).getIMAC().equals("")){
                                    String mac = getInformation.getNewGetInformation(mContext).generateMac();
                                    mLogger.info("agentIP()...没有从..Portal拿到mac程序生成了一个:mac..."+mac);
                                    SharedPreferencesUtils.setParam(mContext, HomeUtil.mFWQMAC,mac);
                                }
                            }
                        }
                        // 是获取的一种样式String Url = "http://172.16.20.203:8080/MobileAltair/jsp/pchome.jsp?userip=172.16.1.12&ac-name=&ssid=altair-SZU&ap-mac=50-DA-00-D1-FD-20&nasip=172.16.1.1&usermac=68-3E-34-63-19-4E&uservlan=2000&userurl=http://baidu.com";
                    }
                }catch (Exception e){
                    mLogger.info("agentIP()...shouldOverrideUrlLoading.. 解析出错。");
                }
                view.loadUrl(url);
                return true;
            }
        });
    }

    /**
     * 用于加载WebView的内部类
     */
    class AgentIpWewView{

        @JavascriptInterface
        public void startFunction(String string){
            mLogger.info("AgentIpWewView()...portal页面发来的地址..isTransferState.."+isTransferState+"String.."+string);
            if(!string.equals("")){
                try {
                    JSONObject jsonObject = new JSONObject(string);
                    String url = jsonObject.getString("url");

                    if(jsonObject.has("url2")){
                        mUri = jsonObject.getString("url2");
                    }

                    if(!isTransferState){
                        getIPState(0,url);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    mOnAgentIpItemClickListener.onItemClick("没有查到");
                }
            }
        }

        @JavascriptInterface
        public String getInterface(){
            return "sendUrl";
        }
    }

    /**
     * 目前是IP的回掉
     * 定义接口 用于itme  的回调
     */
    public interface OnAgentIpItemClickListener {
        void onItemClick(String fwq);
    }

    public interface OnNetworkStateClickListener {
        void onClick(boolean state);
    }

    /**
     * 判断ip 状态
     */
    private void getIPState(final int type,final String url){
        HashMap<String,Object> json = new HashMap<>();
        String id = (String) SharedPreferencesUtils.getParam(mContext, HomeUtil.mUseridDB, "");
        if(id.equals("")){
            json.put("userid",0);
        }else {json.put("userid",id);}
        json.put("visitType",1);
        json.put("ip",getInformation.getNewGetInformation(mContext).getI_IP());
        json.put("mac",getInformation.getNewGetInformation(mContext).getIMAC());
        json.put("apMac",getInformation.getNewGetInformation(mContext).getWiFiMac());
        json.put("apName",getInformation.getNewGetInformation(mContext).getWIFIName());
        json.put("nasid",mNasid[0]);
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(json); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngVersion_isAlive,stringJson,"null","0",time);
        Map map = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,"null","0",Url.mStirngVersion_isAlive,stirngSign,time);
        mLogger.info("判断代理状态-->getIPState()--->"+"fwq--"+url+"....type--"+type+"...stringJson..."+stringJson);
        GreenTreeNetworkUtil.getInstance().doPost(mContext,url,6000,map,new RequestDataCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 1) {
                        mLogger.info("getIPState()--->onSuccess--->" + "String--" + response);
                        isAltairWifi = true;
                        mWebView.destroy();
                        mWebView.removeAllViews();
                        if(!isTransferState){
                            isTransferState = true;
                            mOnAgentIpItemClickListener.onItemClick(url);
                        }
                        if (jsonObject.has("siteAreaid")){
                            if(jsonObject.getInt("siteAreaid") !=0){MyApplication.getApp().setSiteAreaid(jsonObject.getInt("siteAreaid"));}
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable error) {
                mLogger.info("getIPState()--->Throwable--->" + error.toString());
                   if(type == 0){
                       if(mUri !=null && !mUri.equals("")){getIPState(1,mUri);}
                   }
            }
        });
    }
}
